这个概念的名称在Boost Thread源代码中不是最新的,它可能需要是BasicLockable(或者任何更具体的[标准]或扩展概念,如果适用的话)。为了避免混淆,让我们重命名宏参数: template
// Use a little bridge template externallly_locked that controls access to a BankAccount
class externally_locked {
// This macro is used to check that a given template parameter meets certain requirements of
// has certain properties
BOOST_CONCEPT_ASSERT((boost::BasicLockable));
public:
externally_locked(T& obj, LockableT& lockable) : obj_(obj), lockable_(lockable) {}
externally_locked(LockableT& lockable) : obj_(), lockable_(lockable) {}
void set(T const& obj, LockableT& lockable) {
obj_ = obj;
lockable_ = lockable;
}
private:
T obj_;
LockableT& lockable_;
};看它**Live On Coliru** #include
#include
#include
#include
#include
static bool some_condition() { return rand() % 2; }
// Use a little bridge template externallly_locked that controls access to a
// BankAccount
template class externally_locked {
// This macro is used to check that a given template parameter meets
// certain requirements of has certain properties
BOOST_CONCEPT_ASSERT((boost::BasicLockable));
public:
externally_locked(T& obj, LockableT& lockable) : obj_(obj), lockable_(lockable) {}
externally_locked(LockableT& lockable) : obj_(), lockable_(lockable) {}
T& get(boost::strict_lock& lock) {
if (!lock.owns_lock(&lockable_))
throw boost::lock_error(); // run time check throw if not matching locks
return obj_;
}
void set(T const& obj, LockableT& lockable) {
obj_ = obj;
lockable_ = lockable;
}
private:
T obj_;
LockableT& lockable_;
};
class BankAccount {
int balance_;
public:
void Deposit(int amount) { balance_ += amount; }
void Withdraw(int amount) { balance_ -= amount; }
};
class AccountManager : public boost::basic_lockable_adapter {
public:
using lockable_base_type = basic_lockable_adapter;
AccountManager() : checkingAcct_(*this), savingsAcct_(*this) {}
inline void Checking2Savings(int amount);
inline void AMoreComplicatedChecking2Savings(int amount);
private:
externally_locked checkingAcct_;
externally_locked savingsAcct_;
};
void AccountManager::Checking2Savings(int amount) {
boost::strict_lock guard(*this);
checkingAcct_.get(guard).Withdraw(amount);
savingsAcct_.get(guard).Deposit(amount);
}
int main() {
AccountManager mgr;
mgr.Checking2Savings(999);
}要使AccountManager::AMoreComplicatedFunction正常工作,您还需要更多的管道,如教程中所述
|